package com.apes.autoparts.masterdata.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.masterdata.model.EpcBrand;
import com.apes.autoparts.masterdata.repository.EpcBrandRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @ClassName EpcBrandService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/11/19 14:29
 * @Version 1.0
 **/
@Service("epcBrandService")
public class EpcBrandService extends DomainService {
    @Autowired
    private EpcBrandRepository epcBrandRepository;

    @Autowired
    private EpcMasterDataManager epcMasterDataManager;

    public EpcBrand save(SimpleRequest request) throws Exception {
        EpcBrand epcBrand = epcBrandRepository.save(conserve(request));
        //同步至新系统
        Object invoke = invoke("epc.brand.sendSave", MapUtil.mapped(epcBrand));
        //同步至erp
        synErpBrand(epcBrand, "S");
        return epcBrand;
    }

    public EpcBrand update(SimpleRequest request) {
        EpcBrand brand = conserve(request);
        EpcBrand epcBrand = epcBrandRepository.save(brand);
        //同步至新系统
        epcMasterDataManager.synEsb("epc.brand.sendSave", MapUtil.mapped(epcBrand));
        //同步至erp
        synErpBrand(brand, "U");
        return epcBrand;
    }

    public EpcBrand conserve(SimpleRequest request) {
        EpcBrand brand = request.getO(EpcBrand.class);
        brand.setCreatorName(this.getSession(request).getUserName());
        brand.setEntryDate(new Date());
        brand.setTime(DateUtil.format(brand.getEntryDate(), "yyyyMMdd.hhmmss.SSS"));
        return brand;
    }

    public String delete(SimpleRequest request) {
        EpcBrand brand = request.getO(EpcBrand.class);
        epcBrandRepository.delete(brand.getId());
        return "删除成功";
    }

    //同步新增品牌消息(ERP)
    public void synErpBrand(EpcBrand brand, String sign) {
        String method = "S".equals(sign) ? "mdmPpxxService.insert" : "mdmPpxxService.update";
        String TS01 = brand.getTime();
        if ("U".equals(sign)) {
            //更新操作先查询
            TS01 = epcMasterDataManager.getVersion("mdmPpxxService.query", JSONObject.toJSONString(mapper("PPID", brand.getId()))
            );
        }
        Map mapper = mapper("PPID", brand.getId(), "PPMC", brand.getName(), "YWMC", brand.getEnName(), "YXBJ", brand.isValid() ? "1" : "0",
                "CZY", brand.getCreatorName(), "PPLXID", brand.getBrandTypeId(), "PPLXMC", brand.getBrandTypeName(), "PYM", brand.getPinYinMa(),
                "PZID", brand.getQuality().getCode(), "PZMC", brand.getQuality().getDescription(), "TS01", TS01);
        epcMasterDataManager.synErp(method, JSONObject.toJSONString(mapper));
    }
}
